$(document).ready(function() {

  $("#slideshow").owlCarousel({
    navigation : false, // Show next and prev buttons
    slideSpeed : 300,
    paginationSpeed : 400,
    singleItem:true,
    autoPlay:true,
    autoHeight:true,
    scrollPerPage:true
  });

  var owl = $("#ordermenu");
  owl.owlCarousel({
    navigation :false,
    itemsCustom:false,
    scrollPerPage:false,
    items:5,
    itemsMobile:[479,3],
  });

//全局滾動加載變量
var isFinish =false,
  page = 2,
  isLoading = false,
  apiURL = $('#ajax_waterfall').val();
 
  //滾動事件
  function onScroll(event) {
    // console.log('isFinish==='+isFinish);
    // console.log('isLoading==='+isLoading);
    // Only check when we're not still waiting for data.
    var category_id=$("#category_id").val();
    if(!isFinish && !isLoading && ($('#isFinish_'+category_id).length<=0)) {
      var closeToBottom = ($(window).scrollTop() + $(window).height() > $(document).height() - 100);
      var obj=$('#object_ul').val();
      if(closeToBottom) {
        loadData(obj);
      }
    }
  };


  //ajax處理滾動加載
  function loadData(obj) {
    // console.log('location.hash==='+location.hash);
    // console.log('obj==='+obj);
    if(!isFinish && !isLoading && location.hash=='#order'){
      isLoading = true;
      $('#loading').show();
      var category_id=$("#category_id").val();
      var product_string=$('#product_string').val();
      var keywords =  $("#_search").val();
      $.ajax({
        url: apiURL,
        type:'post',
        dataType: 'json',
        cache: false,
        data: {
          'page': page,
          'is_ajax':true,
          'category_id':category_id,
          'product_string':product_string,
          'keywords':keywords,
        }, // Page data
        success:function(data){
          if($.isEmptyObject(data) || typeof data === 'string' || data.product_count <=0){
            isFinish=true;
            var category_name='';
            if(category_id>0){
              category_name=$('a[href="#category_'+category_id+'"]').text();
            }
            if($('#isFinish_'+category_id).length<=0)
				$(obj).append('<div id="isFinish_'+category_id+'" class="isFinish"><p>'+category_name+_common+'</p></div>');
              //$(obj).append('<div id="isFinish_'+category_id+'" class="isFinish"><p>'+category_name+'沒有更多點選了。</p></div>');
          }
          isLoading = false;
          $('#loading').hide();
          if(typeof data.product_html === 'string' && data.product_html !=''){
            page++;
            $(obj).append(data.product_html).fadeIn();
          }
        },
        error:function(){
          console.log('scroll Ajax is Error!');
        }
      });
    }
  }
$(".search i").on("click",function(){
     page = 1;
     isFinish =false;
     var category_id=$("#category_id").val();
     var obj = $('#object_ul').val();
       $(obj).html('');
       loadData(obj);
    
})
  // 滾動加載菜品.
  // $(document).bind('scroll', onScroll);
  var Sys = {};
  var ua = navigator.userAgent.toLowerCase();
  if (window.ActiveXObject)
    Sys.ie = ua.match(/msie ([\d.]+)/)[1];
  if(Sys.ie && parseInt(Sys.ie)>=6 && parseInt(Sys.ie)<=8)
    $(window).scroll(function (){onScroll(scroll)});
  else
    $(document).bind('scroll', onScroll);


  //類別選項卡展示
  $('#ordermenu a').click(function(){
    $('#ordermenu div').removeClass('active');
    $(this).parent('div.item').addClass('active');
    var category_id=$(this).attr('category_id');
    var product_string=$('#product_string').val();
    var obj=$(this).attr('href');
    var obj_item=$(obj).children('li').length;
    $('div.ui-content > ul').each(function(){
      $(this).hide();
    });
    $('#object_ul').val(obj);
    $('#category_id').val(category_id);
    isFinish =false;page = 2;isLoading = false; //重置條件
    console.log(category_id+'===category_id');
    if(obj_item<=0 && $('#isFinish_'+category_id).length<=0){
      $.ajax({
        url: apiURL,
        type:'post',
        data:{
          'category_id':category_id,
          'product_string':product_string,
          'is_ajax':true
        },
        beforeSend:function(){
          $('#loading').show();
        },
        success:function(data){
          $('#loading').hide();
          if($.isEmptyObject(data) || typeof data === 'string' || data.product_count <=0){
            var category_name='';
            if(category_id>0){
              category_name=$('a[href="#category_'+category_id+'"]').text();
            }
            if($('#isFinish_'+category_id).length<=0)
              //$(obj).append('<div id="isFinish_'+category_id+'"  class="isFinish">'+category_name+'沒有更多點選了。</div>').fadeIn();
		  $(obj).append('<div id="isFinish_'+category_id+'"  class="isFinish">'+category_name+_common+'</div>').fadeIn();
          }
          if(typeof data.product_html === 'string' && data.product_html !=''){
            $(obj).html(data.product_html).fadeIn();
          }
        },
        error:function(){
          console.log('Categorys Ajax is Error!');
        }
      });
    }else{
      $(obj).fadeIn();
    }
  });

}); // document end


//object to string
function obj2str(o){
  var r = [];
  if(typeof o =="string") return "\""+o.replace(/([\'\"\\])/g,"\\$1").replace(/(\n)/g,"\\n").replace(/(\r)/g,"\\r").replace(/(\t)/g,"\\t")+"\"";
    if(typeof o == "object"){
      if(!o.sort){
        for(var i in o)
          r.push(i+":"+obj2str(o[i]));
        if(!!document.all && !/^\n?function\s*toString\(\)\s*\{\n?\s*\[native code\]\n?\s*\}\n?\s*$/.test(o.toString)){
          r.push("toString:"+o.toString.toString());
        }
        r="{"+r.join()+"}"
      }else{
        for(var i =0;i<o.length;i++)
          r.push(obj2str(o[i]))
        r="["+r.join()+"]"
      }
      return r;
    }
    return o.toString();
}

var initPhotoSwipeFromDOM = function(gallerySelector) {
    var parseThumbnailElements = function(el) {
        var thumbElements = el.childNodes,
            numNodes = thumbElements.length,
            items = [],
            figureEl,
            childElements,
            linkEl,
            size,
            item;
        for(var i = 0; i < numNodes; i++) {
            figureEl = thumbElements[i]; // <figure> element
            // include only element nodes 
            if(figureEl.nodeType !== 1) {
                continue;
            }
            linkEl = figureEl.children[0]; // <a> element
            size = linkEl.getAttribute('data-size').split('x');
            // create slide object
            item = {
                src: linkEl.getAttribute('href'),
                w: parseInt(size[0], 10),
                h: parseInt(size[1], 10)
            };
            if(figureEl.children.length > 1) {
                // <figcaption> content
                item.title = figureEl.children[1].innerHTML; 
            }
 
            if(linkEl.children.length > 0) {
                // <img> thumbnail element, retrieving thumbnail url
                item.msrc = linkEl.children[0].getAttribute('src');
            } 
            item.el = figureEl; // save link to element for getThumbBoundsFn
            items.push(item);
        }
        return items;
    };
    var closest = function closest(el, fn) {
        return el && ( fn(el) ? el : closest(el.parentNode, fn) );
    };
    var onThumbnailsClick = function(e) {
        e = e || window.event;
        e.preventDefault ? e.preventDefault() : e.returnValue = false;

        var eTarget = e.target || e.srcElement;

        var clickedListItem = closest(eTarget, function(el) {
            return (el.tagName && el.tagName.toUpperCase() === 'FIGURE');
        });

        if(!clickedListItem) {
            return;
        }
        var clickedGallery = clickedListItem.parentNode,
            childNodes = clickedListItem.parentNode.childNodes,
            numChildNodes = childNodes.length,
            nodehome = 0,
            home;

        for (var i = 0; i < numChildNodes; i++) {
            if(childNodes[i].nodeType !== 1) { 
                continue; 
            }

            if(childNodes[i] === clickedListItem) {
                home = nodehome;
                break;
            }
            nodehome++;
        }



        if(home >= 0) {
            openPhotoSwipe( home, clickedGallery );
        }
        e.cancelBubble = true;//取消事件冒泡
        return false;
    };
    // parse picture home and gallery home from URL (#&pid=1&gid=2)
    var photoswipeParseHash = function() {
        var hash = window.location.hash.substring(1),
        params = {};

        if(hash.length < 5) {
            return params;
        }

        var vars = hash.split('&');
        for (var i = 0; i < vars.length; i++) {
            if(!vars[i]) {
                continue;
            }
            var pair = vars[i].split('=');  
            if(pair.length < 2) {
                continue;
            }           
            params[pair[0]] = pair[1];
        }

        if(params.gid) {
            params.gid = parseInt(params.gid, 10);
        }

        if(!params.hasOwnProperty('pid')) {
            return params;
        }
        params.pid = parseInt(params.pid, 10);
        return params;
    };
    var openPhotoSwipe = function(home, galleryElement, disableAnimation) {
        var pswpElement = document.querySelectorAll('.pswp')[0],
            gallery,
            options,
            items;
        items = parseThumbnailElements(galleryElement);
        // define options (if needed)
        options = {
            home: home,

            // define gallery home (for URL)
            galleryUID: galleryElement.getAttribute('data-pswp-uid'),

            getThumbBoundsFn: function(home) {
                // See Options -> getThumbBoundsFn section of docs for more info
                var thumbnail = items[home].el.getElementsByTagName('img')[0], // find thumbnail
                    pageYScroll = window.pageYOffset || document.documentElement.scrollTop,
                    rect = thumbnail.getBoundingClientRect(); 

                return {x:rect.left, y:rect.top + pageYScroll, w:rect.width};
            },
            // history & focus options are disabled on CodePen
            // remove these lines in real life: 
           history: false,
           focus: false 
        };
        if(disableAnimation) {
            options.showAnimationDuration = 0;
        }
        // Pass data to PhotoSwipe and initialize it
        gallery = new PhotoSwipe( pswpElement, PhotoSwipeUI_Default, items, options);
        gallery.init();
    };
    // loop through all gallery elements and bind events
    var galleryElements = document.querySelectorAll( gallerySelector );

    for(var i = 0, l = galleryElements.length; i < l; i++) {
        galleryElements[i].setAttribute('data-pswp-uid', i+1);
        galleryElements[i].onclick = onThumbnailsClick;
    }
    // Parse URL and open gallery if it contains #&pid=3&gid=1
    var hashData = photoswipeParseHash();
    if(hashData.pid > 0 && hashData.gid > 0) {
        openPhotoSwipe( hashData.pid - 1 ,  galleryElements[ hashData.gid - 1 ], true );
    }
};
// execute above function
initPhotoSwipeFromDOM('.my-simple-gallery');